package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.impl.RoleServiceImpl;
import cn.wolfcode.util.PermissionAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService service;

    @Autowired
    private IPermissionService permissionService;

    @PermissionAnnotation(name = "角色列表",expression = "role.list")
    @RequestMapping("/list")
    public String list(Model model, EmployeeQueryObject qo){
        model.addAttribute("PageInfo",service.getPageInfo(qo));
        return "role/list";
    }

    @PermissionAnnotation(name = "角色编辑页面",expression = "role.input")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        model.addAttribute("permission",permissionService.getAll());
        model.addAttribute("role",service.getOne(id));
        model.addAttribute("p",service.selectPermission(id));
        return "role/input";
    }

    @PermissionAnnotation(name = "角色删除",expression = "role.delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        service.deleteRoleByOne(id);
        service.deleteRoleAndPermission(id);
        return "redirect:/role/list";
    }

    @PermissionAnnotation(name = "角色保存",expression = "role.saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Long[] ids,Role role){
        if (role.getId()==null){
            service.insert(role);
            if (ids!=null&&ids.length>0){
                for (Long id : ids) {
                    service.insertPermission(role.getId(),id);
                }
            }
        }else {
            service.deleteRoleAndPermission(role.getId());
            service.update(role);
            if (ids!=null&&ids.length>0){
                for (Long id : ids) {
                    service.insertPermission(role.getId(),id);
                }
            }
        }
        return "redirect:/role/list";
    }
}
